<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="项目名称" prop="name">
                <el-input
                    v-model="queryParams.name"
                    placeholder="请输入项目名称"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                >删除
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <!--      <el-table-column label="${comment}" align="center" prop="id" />-->
            <el-table-column label="项目名称" align="center" prop="name"/>
            <el-table-column label="项目地址" align="center" prop="address"/>
            <el-table-column label="管理员" align="center" prop="manageName"/>
<!--            <el-table-column label="计费方式" align="center">-->
<!--                <template slot-scope="scope">-->
<!--                    {{scope.row.billObj.value==='1' ?'最大需量':'基本容量'}}-->
<!--                </template>-->
<!--            </el-table-column>-->
            <el-table-column label="报警通知" align="center" prop="alarm">
                <template slot-scope="scope">
                    {{scope.row.alarm===0 || scope.row.alarm===null?'开启':'关闭'}}
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80" align="center">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
                </template>
            </el-table-column>
<!--            <el-table-column label="虚拟需量" align="center">-->
<!--                <template slot-scope="scope">-->
<!--                    {{scope.row.virtualObj.value}}-->
<!--                </template>-->
<!--            </el-table-column>-->
            <el-table-column label="备注" align="center" prop="remark"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                    >修改
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNo"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改项目对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px" v-loading="loading">
                <el-form-item label="项目名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入项目名称"/>
                </el-form-item>
                <el-form-item label="项目地址" prop="address">
                    <el-input v-model="form.address" placeholder="请输入项目地址"/>
                </el-form-item>
                <el-form-item label="管理员" prop="manageName">

                    <el-col :span="15">
                        <el-input
                            type="text"
                            placeholder="点击选择项目管理员"
                            v-model="form.manageName"
                            @click.native="allocationProjectAdmin"
                        />

                    </el-col>

                    <el-col :span="5">
                        <div style="margin-left: 5px">
                            <el-button type="primary" plain @click="clearManager">清空</el-button>
                        </div>
                    </el-col>
                </el-form-item>
<!--                <el-form-item label="管理员角色" prop="manageRoleId">-->
<!--                    <el-select-->
<!--                        v-model="form.manageRoleId"-->
<!--                        placeholder="请选择管理员角色"-->
<!--                        clearable-->
<!--                        v-show="roleList.length>0"-->
<!--                    >-->
<!--                        <el-option-->
<!--                            v-for="item in roleList"-->
<!--                            :key="item.id"-->
<!--                            :label="item.name"-->
<!--                            :value="item.id"-->
<!--                        />-->
<!--                    </el-select>-->
<!--                    <div style="cursor: pointer;display: flex" v-if="roleList.length===0">-->
<!--                        <span>该项目下暂无角色</span>-->
<!--                        <el-button type="primary" style="margin-left: 10px" size="mini" @click="openProjectRole=true;formProjectRole.projectId=tempProjectId">-->
<!--                            添加-->
<!--                        </el-button>-->
<!--                    </div>-->
<!--                </el-form-item>-->

                <!-- 添加或修改项目角色对话框 -->
<!--                <el-dialog title="添加项目角色" :visible.sync="openProjectRole" width="800px" append-to-body>-->
<!--                    <el-form ref="formProjectRole" :model="formProjectRole" :rules="rules" label-width="120px">-->
<!--                        <el-form-item label="角色名称" prop="name">-->
<!--                            <el-input v-model="formProjectRole.name" placeholder="请输入角色名称"/>-->
<!--                        </el-form-item>-->
<!--                        <el-form-item label="角色标识" prop="code">-->
<!--                            <el-input v-model="formProjectRole.code" placeholder="请输入角色标识"/>-->
<!--                        </el-form-item>-->
<!--                        <el-form-item label="角色顺序" prop="sort">-->
<!--                            <el-input-number v-model="formProjectRole.sort" :min="0"/>-->
<!--                        </el-form-item>-->
<!--                        <el-form-item label="备注" prop="remark">-->
<!--                            <el-input v-model="formProjectRole.remark" type="textarea" placeholder="请输入内容"/>-->
<!--                        </el-form-item>-->
<!--                    </el-form>-->
<!--                    <div slot="footer" class="dialog-footer">-->
<!--                        <el-button type="primary" @click="submitProjectRoleForm">确 定</el-button>-->
<!--                        <el-button @click="openProjectRole=false">取 消</el-button>-->
<!--                    </div>-->
<!--                </el-dialog>-->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="报警通知" prop="alarm">
                            <el-radio-group v-model="form.alarm" size="small">
                                <el-radio-button :label="0">开启</el-radio-button>
                                <el-radio-button :label="1">关闭</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="通知方式" v-if="form.alarm === 0">
                            <el-checkbox-group v-model="noticeWayList" @change="changeNoticeWay">
                                <el-checkbox label="短信"></el-checkbox>
                                <el-checkbox label="邮箱"></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                </el-row>


                <div v-for="(item,index) in form.configs" :key="index">
                    <el-form-item :label="item.name" v-if="item.name==='计费方式'">
                        <el-switch
                            v-model="item.value"
                            active-value="1"
                            inactive-value="0"
                            active-text="最大需量"
                            inactive-text="基本容量"
                        >
                        </el-switch>
                    </el-form-item>
                </div>

                <el-form-item label="状态" prop="status">
                    <el-select v-model="form.status" placeholder="项目状态" clearable size="small">
                        <el-option
                            v-for="dict in dict.type.sys_normal_disable"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                        />
                    </el-select>
                </el-form-item>
                <div v-for="(item,index) in form.configs" :key="index">
                    <el-form-item :label="item.name" v-if="item.name==='虚拟需量'">
                        <el-input v-model="item.value" placeholder="请输入虚拟需量"/>
                    </el-form-item>
                </div>

                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog :title="allocationTitle" :visible.sync="allocationOpen" width="500px" append-to-body>
            <el-form :model="allocationQueryParams" ref="allocationQueryForm" :rules="allocationQueryRules"
                     :inline="true" label-width="85px" @submit.native.prevent
            >
                <el-form-item label="手机号码" prop="mobile">
                    <el-input
                        v-model="allocationQueryParams.mobile"
                        placeholder="请输入手机号码搜索用户"
                        clearable
                        size="small"
                        @keyup.enter.native="selectUser"
                    />
                </el-form-item>

                <el-form-item label="用户名称" prop="username">
                    <el-input
                        v-model="allocationQueryParams.username"
                        placeholder="请输入用户名称搜索用户"
                        clearable
                        size="small"
                        @keyup.enter.native="selectUser"
                    />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="selectUser">搜索</el-button>
                </el-form-item>
            </el-form>

            <el-table :data="userList" height="250" border style="width: 100%">
                <el-table-column prop="username" label="用户名称" align="center" width="150"/>
                <el-table-column prop="mobile" label="手机号码" align="center" width="200"/>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button type="primary" size="small" @click="choose(scope.row)">
                            选择
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { listProject, getProject, addProject, updateProject, delProject } from '@/api/system/project'
import { searchPersonalUser2 } from '@/api/business/personalUser'
import { addRole, getProjectRoleListSimple } from '@/api/system/projectRole'
import { getConfigListSimple } from '@/api/infra/config'
import store from '@/store'

export default {
    dicts: ['sys_normal_disable'],
    name: 'ProjectList',
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            allocationTitle: '',
            allocationOpen: false,
            // 角色列表
            roleList: [],
            allocationQueryParams: {
                pageNo: 1,
                pageSize: 10,
                mobile: null,
                username: null
            },
            allocationQueryRules: {
                // mobile: [
                //   { required: true, trigger: 'blur', message: '请输入手机号码' }
                // ]
            },
            // 项目表格数据
            projectList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            openProjectRole: false,
            // 查询参数
            queryParams: {
                pageNo: 1,
                pageSize: 10,
                name: null,
                projectRoleKey: null,
                projectRoleSort: null
            },
            // 表单参数
            form: {
                alarm: 1,
                manageRoleId: null,
                manageName:'',
                status:'0',
                remark:'',
                configs:[],
            },
            formProjectRole: {
                projectId: null
            },
            // 表单校验
            rules: {
                name: [
                    { required: true, message: '项目名称不能为空', trigger: 'blur' }
                ]
            },
            menuOpen: false,
            menuForm: {},
            menuRules: {},
            menuExpand: false,
            menuNodeAll: false,
            menuOptions: [],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            managerProject: {
                manageId: null,
                projectId: null
            },
            noticeWayList: [],
            userList: [],
            tempProjectId: null
        }
    },
    created() {
        this.getList()
    },
    computed: {
        ...mapGetters([
            'projectId'
        ])
    },
    methods: {
        // 获取角色列表
        getRoleList() {
            let obj = {
                projectId: this.tempProjectId
            }
            getProjectRoleListSimple(obj).then(res => {
                this.roleList = res.data
            })
        },
        /** 查询项目列表 */
        getList() {

            this.loading = true

            // this.queryParams.projectId = this.projectId
            listProject(this.queryParams).then(response => {
                // response.data.list.forEach(item=>{
                //     item.billObj = item.configs.find(config => config.name === "计费方式") || {};
                //     item.virtualObj = item.configs.find(config => config.name === "虚拟需量") || {};
                // })
                this.projectList = response.data.list
                this.total = response.data.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
        },
        // 表单重置
        reset() {
            this.form = {
                name: '',
                address: '',
                remark: '',
                alarm: 1,
                alarmWay: [],
                configs:[],
                status:'0'
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNo = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加项目'
            this.getRoleList()
            this.getConfigList()
        },
        // 获取配置列表
        getConfigList(){
            this.loading = true
            getConfigListSimple('project').then(response => {
                console.log('response',response.data)
                this.form.configs = response.data
                this.loading = false
            }).catch(error=>{
                this.loading = false
            })
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            this.tempProjectId = row.id
            this.getRoleList()
            getProject(id).then(response => {
                this.form = response.data
                if(this.form.status!==null){
                    this.form.status = this.form.status.toString()
                }
                console.log(this.form)
                this.open = true
                this.title = '修改项目'
            })
        },
        // 选择警告方式
        changeNoticeWay(val) {
            console.log(val)
        },
        allocationProjectAdmin() {
            this.allocationTitle = '分配项目管理员'
            this.allocationOpen = true
            this.managerProject.projectId = parseInt(this.ids[0])
        },
        selectUser() {
            if (this.allocationQueryParams.username != null || this.allocationQueryParams.mobile != null) {
                searchPersonalUser2(this.allocationQueryParams).then(response => {
                    if (response.data.list.length === 0) {
                        this.$message.info('用户不存在')
                    }
                    this.userList = response.data.list
                })
            } else {
                this.$message.warning('请输入手机号或用户名查询用户')
            }
        },
        clearManager() {
            this.form.manageId = null
            this.form.manageName = null
        },

        choose(row) {
            this.form.manageId = row.id
            this.form.manageName = row.username === null ? row.nickname : row.username
            this.allocationOpen = false
            this.allocationQueryParams.mobile = null
            this.allocationQueryParams.username = null
            this.userList = null

        },
        /** 提交添加角色按钮 */
        submitProjectRoleForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    addRole(this.formProjectRole).then(response => {
                        this.$modal.msgSuccess('新增成功')
                        this.openProjectRole = false
                        this.getRoleList()
                    })
                }
            })
        },

        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form.alarm === 0) {
                        if (this.noticeWayList.length === 0) {
                            this.$modal.msgError('请选择通知方式')
                            return
                        }
                        this.form.alarmWay = []
                        this.noticeWayList.forEach(item => {
                            console.log(item)
                            if ('短信' === item) {
                                this.form.alarmWay.push(1)
                            }

                            if ('邮箱' === item) {
                                this.form.alarmWay.push(0)
                            }
                        })
                    }
                    console.log(this.form)

                    if (this.form.id != null) {
                        updateProject(this.form).then(response => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addProject(this.form).then(response => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },

        handleDelete(row) {
            const projectIds = row.projectId || this.ids
            this.$modal.confirm('是否确认删除项目编号为"' + projectIds + '"的数据项？').then(function() {
                return delProject(projectIds)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
                if (projectIds.includes(sessionStorage.getItem('projectId'))) {
                    console.log('包含.....')
                    sessionStorage.removeItem('projectId')
                }
                if (projectIds.includes(store.getters.projectId)) {
                    this.$store.dispatch('setProjectId', null)
                }
                // 刷新页面
                this.reload()
            }).catch(() => {
            })
        },

        handleExport() {
            this.download('system/role/export', {
                ...this.queryParams
            }, `role_${new Date().getTime()}.xlsx`)
        }
    }
}
</script>
